<?php

namespace App\Listeners\V1;

use App\Events\AppEvent;
use App\Models\Factory\DeliveryFactory;
use App\Models\Factory\UserFactory;
use Illuminate\Queue\InteractsWithQueue;
use App\Listeners\AppListener;
use App\Helpers\Logger\SLogger;
use Illuminate\Support\Facades\DB;
use App\Helpers\Http\HttpClient;

/**
 * 渠道统计事件监听
 * Class UserRegCountListener
 * @package App\Listeners\V1
 */
class UserRegCountListener extends AppListener
{

    use InteractsWithQueue;

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  AppEvent  $event
     * @return void
     */
    public function handle(AppEvent $event)
    {

        $channel = $event->data;

        DB::beginTransaction();
	    try
	    {
	        if(isset($channel['terminal'])) {
                switch ($channel['terminal']) {
                    case 3:
                        $channel['nid'] = (isset($channel['nid']) && !empty($channel['nid'])) ? $channel['nid'] : 'weixin1';
                        break;
                    case 2 :
                        $channel['nid'] = (isset($channel['nid']) && !empty($channel['nid'])) ? $channel['nid'] : 'ios';
                        break;
                    default:
                        $channel['nid'] = (isset($channel['nid']) && !empty($channel['nid'])) ? $channel['nid'] : 'android';
                        break;
                }
            }


//            $url    =  "http://www.shoujijiekuan.com//Web/CheckTel.aspx?CellNo=".$channel['userphone'];
//            $promise = HttpClient::i()->request('GET', $url);
//            $result = $promise->getBody()->getContents();
//            //结果是0表示在现金贷数据库中没有该手机号，插入流水表做统计
//            if($result == 0)
//            {
//                $user_origin = 1;
//            }else{
//                $user_origin = 2;
//            }
//            $channel['user_origin'] = $user_origin;

			//插入渠道流水表
			$channelLog =  DeliveryFactory::insertDeliverylLog($channel);
		




            //修改渠道主表数据
            if($channelLog && $channel['type'] == 2){
                //拿到用户的id
                $userId = UserFactory::getUserByMobile($channel['userphone'])->id;

                //把渠道号值插入到user表中
                $user = UserFactory::addChannel($userId,$channel['nid']);

                $channelCount = DeliveryFactory::updateDeliveryRegisterCount($channel['nid']);
            }else{
                $user = true;
            }


		    if (!$channelLog || !$user) {
			    DB::rollback();

			    SLogger::getStream()->error('注册渠道统计失败');

		    }
		    else
		    {
			    DB::commit();
		    }
	    }
	    catch (\Exception $e)
	    {
		    DB::rollBack();

		    SLogger::getStream()->error('注册渠道统计失败');
            SLogger::getStream()->error($e);

        }
	    return false;



    }

}
